package cn.javaweb.servlet;

import cn.javaweb.entity.LoginInfo;
import cn.javaweb.entity.User;
import cn.javaweb.group0.model.LogModel;
import cn.javaweb.group0.model.RoleModel;
import cn.javaweb.library.AjaxResult;
import cn.javaweb.library.Token;
import cn.javaweb.library.Util;
import cn.javaweb.model.UserModel;
import com.alibaba.fastjson2.JSON;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try{

            LoginInfo li = JSON.parseObject(Util.getJsonParam(req), LoginInfo.class);
            UserModel userModel = new UserModel();
            RoleModel roleModel = new RoleModel();

            User user = userModel.getUserByNameAndPassword(li.getUsername(), li.getPassword());

            if(user==null){
                resp.getWriter().print( AjaxResult.error("用户名或者密码错误"));
                return;
            }

            String token = Token.generateToken();
            user.setToken(token);
            userModel.updateUserToken(user);

            user.setPassword("******");
            LogModel logModel = new LogModel();
            logModel.addLog(req.getRemoteHost(), req.getRequestURI(), req.getMethod(),"登陆成功",li.getUsername());

            HashMap<String, Object> result = new HashMap<String, Object>();

            List<String> roles = roleModel.getRoles(user);

            result.put("userInfo", user);
            result.put("roles", roles);

            resp.getWriter().print(AjaxResult.success("登陆成功", result));

        }catch (Exception e){
            resp.setContentType("application/json;charset=UTF-8;");
            resp.getWriter().print(AjaxResult.error("登陆失败"));
        }
    }

}
